##
## Analog.py 
##
## Offers stats functionality for web2Admin script.
## (ie RunStats, CreateNewStats, etc)
##
## Author: Shannon Eric Peevey <speeves@erikin.com>, 16 April 2004
##

import os
import re
import Webcontrol 

class AnalogFunc:
    """Offers statistical functionality for web2Admin script.
    (ie create database, create user)"""

    def RunStats(self, config):
        """ Call the webstats.pl file to generate Analog stats """
	runStats = config['General']["usrBinPath"] + "perl ./webstats.pl"
        os.system(runStats);

        print "Now run (20) Generate Static Stats"

    def AddVHostToStatsFile(self, config, vHostName, vHostWebroot, vHostFileName, utilityObject):
        """ Add a new line to the Vhost.txt file """
        # open static_logs.txt
        alllines = utilityObject.GrabTextList(config['Htgroup']['Server' + config['Session']['Htgroup']['CurrentServer']]["pathToVhostFile"])
        newInclude = vHostFileName+ "_access_log:" + vHostWebroot + ":" + vHostName
        
        if config['General']["debugLevel"] == '1':
            print newInclude
        alllines.append(newInclude)

        
    def CreateAnalogSkel(self, config, vHostName, vHostFileName, vHostWebroot, isVHost, utilityObject, webName=''):
        """ Create a new analog.conf for a vHost.  """
        # isVHost == 0 then this is for a web
        # isVHost == 1 then this is for a virtual host
        # if isVHost == 2 then this is for a virtual with a nested root inside another virtual host
        #
        # vHostFileName = www_example_com
        #      where = VHost.txt entry is:
        #            www_example_com_access_log:www_example_com:www.example.com
        #  replace vHostFileName with webroot, when isVHost == 2
        vHostAccessLog = vHostFileName + "_access_log"
        if isVHost == 1:
            vHostStatsIndex = vHostFileName + "_index.htm"
        elif isVHost == 2:
            vHostStatsIndex = vHostFileName + "_" + webName + "_index.htm"
        else:
            vHostStatsIndex = webName + "_index.htm"
            
        # then, open analog.skel and place a new line in the vHost section
        alllines = utilityObject.GrabTextList(config['Analog']['Server' + config['Session']['Analog']['CurrentServer']]["analogSkel"])

        if config['General']["debugLevel"] == '1':
            print vHostFileName

        # we will loop it to help with the ease of use
        for eachline in alllines:
            pattern = '^####DoNotRemove'
            m = re.match(pattern, eachline)
            addEntry = 0
            if m != None:
                confIndex = alllines.index(eachline)
                alllines.remove(eachline)
                newInclude = "# new variables for analog conf\n"
                newInclude2 = "LOGFILE " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["oldApacheLogs"] + vHostAccessLog + "\n"
                newInclude3a = "OUTFILE " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostRoot"] + vHostWebroot + "/stats/index.htm\n"
                newInclude3b = "OUTFILE " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostRoot"] + vHostWebroot + "/stats/" + vHostStatsIndex + "\n"
                newInclude4a = "HOSTNAME '" + vHostName + "'\n"
                newInclude5a = "FILEINCLUDE /*\n"
                newInclude5b = "FILEINCLUDE /" + webName + "*\n"
                newInclude6 = "HOSTURL http://" + vHostName + "\n"
                if isVHost == 1:
                    alllines.insert(confIndex, newInclude + newInclude2 + newInclude3a + newInclude4a + newInclude5a + newInclude6)
                    alllines.insert(confIndex + 1, eachline)
                # elif isVHost == 2:
                #    alllines.insert(confIndex, newInclude + newInclude2 + newInclude3b + newInclude4a + newInclude5a + newInclude6)
                #    alllines.insert(confIndex + 1, eachline)
                else:
                    alllines.insert(confIndex, newInclude + newInclude2 + newInclude3b + newInclude4a + newInclude5b + newInclude6)
                    alllines.insert(confIndex + 1, eachline)

                addEntry = addEntry + 1
                break

        if isVHost == 0:
            # rename file
            copy = config['General']["binPath"] + "cp " + config['analog']["analogSkel"] + " " + config['General']["tempPath"] + vHostFileName + "_" + webName + ".cfg"
            if config['General']["debugLevel"] == '1':
                print copy            
            os.system(copy)
            
            # open the destination file
            destination_file = open(config['General']["tempPath"] + vHostFileName + "_" + webName + '.cfg', 'w')
            # write lines into file
            destination_file.writelines(alllines)
            # close the destination file
            destination_file.close()
            
            # move file to /etc/analog
            move = config['General']["binPath"] + "mv " + config['General']["tempPath"] + vHostFileName + "_" + webName + ".cfg " + config['AnalogDict']["analogConf"]
            if config['General']["debugLevel"] == '1':
                print move
            os.system(move)
        elif isVHost == 1:
            # rename file
            copy = config['General']["binPath"] + "cp " + config['Analog']['Server' + config['Session']['Analog']['CurrentServer']]["analogSkel"] + " " + config['General']["tempPath"] + vHostFileName + ".cfg"
            if config['General']["debugLevel"] == '1':
                print copy   
            os.system(copy)

            # open the destination file
            destination_file = open(config['General']["tempPath"] + vHostFileName + '.cfg', 'w')
            # write lines into file
            destination_file.writelines(alllines)
            # close the destination file
            destination_file.close()
            
            # move file to /etc/analog
            move = config['General']["binPath"] + "mv " + config['General']["tempPath"] + vHostFileName + ".cfg " + config['Analog']['Server' + config['Session']['Analog']['CurrentServer']]["analogConf"]
            if config['General']["debugLevel"] == '1':
                print move
            os.system(move)
        else:
            # rename file
            copy = config['General']["binPath"] + "cp " + config['Analog']['Server' + config['Session']['Analog']['CurrentServer']]["analogSkel"] + " " + config['General']["tempPath"] + vHostWebroot + "_" + webName + ".cfg"
            if config['General']["debugLevel"] == '1':
                print copy   
            os.system(copy)

            # open the destination file
            destination_file = open(config['General']["tempPath"] + vHostWebroot + '_' + webName + '.cfg', 'w')
            # write lines into file
            destination_file.writelines(alllines)
            # close the destination file
            destination_file.close()
            
            # move file to /etc/analog
            move = config['General']["binPath"] + "mv " + config['General']["tempPath"] + vHostWebroot + "_" + webName + ".cfg " + config['Analog']['Server' + config['Session']['Analog']['CurrentServer']]["analogConf"]
            if config['General']["debugLevel"] == '1':
                print move
            os.system(move)

        
    def GenerateStaticStats(self, config):
        """ get a directory listing of files in /etc/analog """
        filelist = os.listdir(config['Analog']['Server' + config['Session']['Analog']['CurrentServer']]["analogConf"])

        for i in filelist:
            comm = config['Analog']['Server' + config['Session']['Analog']['CurrentServer']]["analogBin"] + " -G +C'CONFIGFILE " + config['Analog']["analogConf"] + i + "'"
            if config['General']["debugLevel"] == '1':
                print comm
            os.system(comm)

    def GenerateNewStatsFile(self, config, utilityObject):
        """ Create a new stats file...? """
        webName = ''
       	viewVhost = raw_input("Would you like to view existing virtual hosts? (y/n)")
        vHostTextList = utilityObject.GrabTextList(config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["pathToVhostFile"])
        if viewVhost == 'y':
            # grab the list of virtual hosts
            print "\nThese are the existing Virtual Hosts:\n"
            webcontrolObject = Webcontrol.ApacheFunc()
            webcontrolObject.FormattedSplitURLWebroot(config, vHostTextList)

        print "\nNOTE: Format is FQDN => webroot.  Webroots should be viewed as: /var/wwww\n"

        print "Please, choose one of the following:"
        print "(0) Web"
        print "(1) Virtual Host"
        print "(2) Virtual Host with a Nested web root"
        print "   (ie www.nestedroot.com => /var/www/subweb/here.  Where www.example.com => /var/www )\n"
        
        isVHost = input('What is the web type? (0/1/2) ')
        
        vHostName = raw_input('Which FQDN would you like to choose? (ie www.example.com) ')
        vHostFileName = re.sub('\.', '_', vHostName)
        # search VHost.txt for webroot
        for lines in vHostTextList:
            if lines[0] == "#" or lines[0] == '\n':
                continue
            else:
                splitVHost = re.split(':', lines)
                splitVHost2 = splitVHost[2]
                if splitVHost2[:-1] == vHostName:
                    vHostWebroot = splitVHost[1]
                    break

        try:
            vHostWebroot
        except:
            vHostWebroot = ''
        # web name
        if isVHost == 0 or isVHost == 2:
            viewWebs = raw_input("Would you like to view the webs in this virtual host? (y/n) ")
            if viewWebs == 'y':
                filelist = os.listdir(config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostRoot"] + vHostWebroot + '/')
                for folder in filelist:
                    print folder
            
            webName = raw_input("What is the webname? ")

        if config['General']["debugLevel"] == '1':
            print "The vHostName is", vHostName
            print "The vHostFileName", vHostFileName
            print "The vHostWebroot", vHostWebroot
            print "The webName is", webName
            print "The conf file name is", vHostFileName + webName + ".cfg"
        
        self.CreateAnalogSkel(config, vHostName, vHostFileName, vHostWebroot, isVHost, utilityObject, webName)
        
        del webcontrolObject
